package com.study.demo_spel;

import com.study.demo_spel.entity.Inventor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootApplication
public class DemoSpelApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoSpelApplication.class, args);
        ExpressionParser parser = new SpelExpressionParser();
        Inventor inventor = new Inventor();
        EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
        //设置值
        parser.parseExpression("name").setValue(context, inventor, "Aleksandar Seovic");
        System.out.println(inventor);

        //设置值
        String aleks = parser.parseExpression(
                "name = 'Aleksandar Seovic'").getValue(context, inventor, String.class);
        System.out.println(inventor);
        //声明List
        List listOfLists = (List) parser.parseExpression("{{'a','b'},{'x','y'}}").getValue(context);
        System.out.println(listOfLists);
        //声明Map
        Map mapOfMaps = parser.parseExpression("{name:{first:'Nikola',last:'Tesla'},dob:{day:10,month:'July',year:1856}}").getValue(context, Map.class);
        System.out.println(mapOfMaps);
        //default value
        String name = parser.parseExpression("name?:'Unknown'").getValue(inventor, String.class);
        System.out.println(name);
        //check null
        String city = parser.parseExpression("name?.length").getValue(context, inventor, String.class);
        System.out.println(city);
        //筛选符合表达式的值（value<27）组成新的map
        context.setVariable("map",generateMap());
        Map newMap = (Map) parser.parseExpression("#map.?[value<27]").getValue(context);
        System.out.println(newMap);
    }

    private static Map<String,Integer> generateMap() {
        Map<String,Integer> map=new HashMap<>();
        for (int i = 0; i < 100; i++) {
            map.put("key:"+i,i);
        }
        return map;
    }

}
